"""
jinja2 module -> template files + .json = object file
"""
import os
import jinja2
import json
import datetime

__version__ = '1.0.0'


class CodeGenerator:
    template_file_suffix = 'template'

    def __init__(self, module_name, rules_name):
        self._module_name = module_name
        self._rules_name = rules_name

        self.template_files = []

    def load_rules(self, rules_name : str = None):
        if rules_name: self._rules_name = rules_name
        rules_file = os.path.join("project", "configure", self._module_name, "rules", self._rules_name + '.json')
        rules = {}
        if os.path.isfile(rules_file):
            with open(rules_file, 'r', encoding = 'utf-8') as f:
                rules = json.load(f)
        return rules['rules']

    def save_rules(self, rules : dict):
        out = {}
        out['version'] = __version__
        out.update({'rules': rules})
        with open(os.path.join("project", "configure", self._module_name, "rules", self._rules_name + '.json'), 'w', encoding = 'utf-8') as f:
            f.write(json.dumps(out, indent = 4, ensure_ascii = False))

    def read_template(self, folder_name : str):
        self._folder_name = folder_name
        path = os.path.join("project", "configure", self._module_name, "templates", self._folder_name)
        for file in os.listdir(path):  # os.listdir(project\configure\Nvm\template\src)
            if file.split('.')[1] == self.template_file_suffix:
                self.template_files.append(file)

    def generator(self, rules : dict, template_name : str, out_name : str, desc : str):
        self.save_rules(rules)

        env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path.join("project", "configure", self._module_name, "templates", self._folder_name)))
        template = env.get_template(template_name)
        content_out = template.render(rules,
                                _description = desc,
                                _file_name = out_name.split('.')[0],
                                _date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                _year = datetime.datetime.now().strftime("%Y") + '\n')

        out_file = os.path.join("output", "components", self._module_name, self._folder_name, out_name)
        os.makedirs(os.path.dirname(out_file), exist_ok = True)
        with open(out_file, 'w', encoding = 'utf-8') as f:
            f.writelines(content_out)
    
    def GetModelnameRelesname(self):
        return self._module_name,self._rules_name


